<!DOCTYPE html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<%@ taglib prefix="display" uri="/WEB-INF/tags/displaytag-12.tld"%>

<html>
<head>
	<title>NMC - Road Sweeping</title>
	<meta name="decorator" content="Admin_HeaderFooter" />
	<meta name="tab" content="createTrack" />
	<script type="text/javascript"
      src="http://maps.googleapis.com/maps/api/js?key=AIzaSyAlTKyHLgkM8IULM9fIwPbJ96ju_5C-wtg&sensor=false">
    </script>
	
	<script type="text/javascript">
	
	
	
	// The locations array contains the set of text locations making up the polyline.
	var locations = [];
	// The latlngs array contains the set of LatLng objects.
	var latlngs = new google.maps.MVCArray();
	var levels = [];
	// The markers array contains the actual Marker objects.
	var markers = [];
	var displayPath;

	var selectedMarker = null;
	var map;

	// The tempMarker is a marker showing a candidate location.
	var tempMarker = new google.maps.Marker();

	var highlightIcon = new google.maps.MarkerImage(
	  "./images/mm_20_yellow.png",
	  new google.maps.Size(12,20),
	  new google.maps.Size(6,20)
	);

	var tempIcon = new google.maps.MarkerImage(
	  "./images/mm_20_green.png",
	  new google.maps.Size(12,20),
	  new google.maps.Size(6,20)
	);

	var locationIcon = new google.maps.MarkerImage(
	  "./images/mm_20_blue.png",
	  new google.maps.Size(12,20),
	  new google.maps.Size(6,20)
	);

	var newShadow = new google.maps.MarkerImage(
	  "./images/mm_20_shadow.png",
	  new google.maps.Size(22,20),
	  new google.maps.Point(13,13)
	);
	var endMarker = new google.maps.Marker({icon:"./images/mm_20_yellow.png"});
	
	var startMarker = new google.maps.Marker({icon:"./images/mm_20_blue.png"});

	var map;
	// Create the Google Map to be used.
	function initialize() {

	var myOptions = {
	center: new google.maps.LatLng(21.145044913749103, 79.08856766018835),
	zoom: 15,
	mapTypeId: google.maps.MapTypeId.ROADMAP
	        };
	  map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);


	   
	  tempMarker.setOptions({
	    icon: tempIcon,
	    shadow: newShadow,
	    draggable: true
	  });

	  google.maps.event.addListener(map, "click", showTempMarker);

	  displayPath = new google.maps.Polyline({
		map: map,
		strokeColor: "#FF0000",
	    strokeOpacity: 1.0,
	    strokeWeight: 2,
	    path: latlngs
	  })
	  
	  var latlong =document.getElementById('latLong').value;
	  //alert("latLong "+latlong );
	  if(latlong && latlong.length >0){
		  showMap(latlong);
	  }
  
	}

	function showTempMarker(e) {
	 
	 
	  tempMarker.setPosition(e.latLng);

	  document.getElementById('txtLatitude').value = e.latLng.lat();
	  document.getElementById('txtLongitude').value = e.latLng.lng();

	  google.maps.event.addListener(tempMarker, "drag", function() {
	    document.getElementById('txtLatitude').value = tempMarker.getPosition().lat();
	    document.getElementById('txtLongitude').value = tempMarker.getPosition().lng();
	  });

	  tempMarker.setMap(map);
	}

	// Add a location to the location list.
	function addLocationFromInput() {
	  var lat = document.getElementById('txtLatitude').value;
	  var pLat = parseFloat(lat);

	  if (pLat.toString() != lat) {
	    alert('Invalid latitude entered. Must be in range of -90 to 90');
	    return;
	  }

	  if (pLat < -90 || pLat > 90) {
	    alert('Invalid latitude entered. Must be in range of -90 to 90');
	    return;
	  }

	  var lng = document.getElementById('txtLongitude').value;
	  var pLong = parseFloat(lng);

	  if (pLong.toString() != lng) {
	    alert('Invalid longitude entered. Must be in range of -180 to 180');
	    return;
	  }

	  if (pLong < -180 || pLong > 180) {
	    alert('Invalid longitude entered. Must be in range of -180 to 180');
	    return;
	  }

	  var level = document.getElementById('txtLevel').value;
	  var pLevel = parseInt(level);

	  if (pLevel.toString() != level) {
	    alert('Invalid minimum level entered. Must be in range of 0 to 3');
	    return;
	  }

	  if (pLevel < 0 || pLevel > 3) {
	    alert('Invalid minimum level entered. Must be in range of 0 to 3');
	    return;
	  }

	  addLocation(lat, lng, pLevel);
	}

	function addLocation(lat, lng, level) {
	 
	  var newLocation = new google.maps.LatLng(lat, lng);
	  markers.push(createLocationMarker(newLocation));
	  addLocationToList(lat, lng, level);
	  latlngs.push(newLocation);
	  levels.push(level);
	  displayPath.setPath(latlngs);
	  //showEncoding();
	}

	function createLocationMarker(location) {
	  if (tempMarker) {
	    tempMarker.setMap(null);
	  }
	  
	  var locationMarker = new google.maps.Marker();

	  locationMarker.setOptions({
	    icon: locationIcon,
	    shadow: newShadow,
	    draggable: true,
	    map: map,
	    position: location
	  });
	  
	  google.maps.event.addListener(locationMarker, "click", function() {
	    highlight(findMarkerIndex(locationMarker));
	  });

	  google.maps.event.addListener(locationMarker, "drag", function() {
	    var index = findMarkerIndex(locationMarker);

	    if (index >= 0) {
	      var nLatLng = locationMarker.getPosition();
	      latlngs.setAt(index, nLatLng);

	      var nLat = nLatLng.lat();
	      var nLng = nLatLng.lng();

	      var pLevel = locations[index].Level;

	      var modifiedLocation = {
	        Latitude: nLat,
	        Longitude: nLng,
	        Level: pLevel
	      };

	      displayPath.setPath(latlngs);
	      locations[index] = modifiedLocation;
	      document.getElementById('locations').options[index]
	        = new Option('' + nLat + ',' + nLng + '', index);
	      highlight(index);
	      showEncoding();
	    }
	  });
	  
	  return locationMarker;
	} 

	// Creates a location and adds it to the list.
	function addLocationToList(lat, lng, pLevel) {

	  // Add the location to the UI
	  var displayLocation = new Option('' + lat + ',' + lng + '' ,
	                                locations.length);
	  document.getElementById('locations').options.add(displayLocation);
	  
	  // Create a text location for the array
	  var newLocation = {
	    Latitude: lat,
	    Longitude: lng,
	    Level: pLevel
	  };

	  locations.push(newLocation);
	}

	// Returns the index of the marker in the polyline.
	function findMarkerIndex(locationMarker) {
	  var index = -1;

	  for (var  i = 0; i < markers.length; ++i) {
	    if (markers[i] == locationMarker) {
	      index = i;
	      break;
	    }
	  }

	  return index;
	}

	// Highlights the location specified by index in both the map and the location list.
	function highlight(index) {

	  if (selectedMarker == null) {
	    selectedMarker = markers[index];
	  }
	  if (selectedMarker != markers[index]) {
	    selectedMarker.setIcon(locationIcon);
	  }
	  
	  markers[index].setIcon(highlightIcon);
	  selectedMarker = markers[index];

	  // Mark which location is selected.
	  if (index < locations.length) {
	    locations.selected = index;
	    document.getElementById('locations').options[index].selected = true;
	  }
	}

	// Delete a location
	function deleteLocation() {
	  if (locations.length > 0) {
	    var locationToRemove = document.getElementById('locations').selectedIndex;

	    if (locationToRemove >= 0 && locationToRemove < locations.length) {
	      locations.splice(locationToRemove, 1);

	      if (selectedMarker == markers[locationToRemove]) {
	        selectedMarker = null;
	      }

	      markers[locationToRemove].setMap(null);
	      markers.splice(locationToRemove, 1);
	      document.getElementById('locations').options[locationToRemove] = null;
	      
	      latlngs.removeAt(locationToRemove);
	      levels.splice(locationToRemove, 1);
	      displayPath.setPath(latlngs);      
	      showEncoding();
	    }

	    if (locations.length > 0) {
	      if (locationToRemove == 0) {
	        locationToRemove++;
	      }
	    }
	  }
	}

	// Delete *all* the locations from the polyline, with confirmation dialog before
	// deletion.
	function deleteAllLocations() {
	  var deleteConfirm = confirm("Are you sure you want to remove all the locations"
	                              + " from this polyline?");

	  if (deleteConfirm) {
	    document.getElementById('locations').options.length = 0;
	    locations = [];
	    for(var i = 0; i < markers.length; ++i) {
	      var markerToRemove = markers[i];
	      markerToRemove.setMap(null);
	    }
	    markers = [];
	    latlngs = new google.maps.MVCArray();
	    levels = [];
	    displayPath.setPath(latlngs);
	    showEncoding();    
	  }
	}

	function showEncoding() {
	  var encodeString = google.maps.geometry.encoding.encodePath(latlngs);
	  document.getElementById('encodedPolyline').value = encodeString;
	  
	  var encodeLevelsString = "";
	  for (i = 0; i < levels.length ; i++) {
	    encodeLevelsString += encodeNumber(levels[i]);
	  }
	  document.getElementById('encodedLevels').value = encodeLevelsString;
	}

	// Encode an unsigned number in the encode format.
	function encodeNumber(num) {
	  var encodeString = "";
	 
	  while (num >= 0x20) {
	    encodeString += (String.fromCharCode((0x20 | (num & 0x1f)) + 63));
	    num >>= 5;
	  }
	 
	  encodeString += (String.fromCharCode(num + 63));
	  return encodeString;
	}

	// Decode an encoded levels string into an array of levels.
	function decodeLevels(encodedLevelsString) {
	  var decodedLevels = [];

	  for (var i = 0; i < encodedLevelsString.length; ++i) {
	    var level = encodedLevelsString.charCodeAt(i) - 63;
	    decodedLevels.push(level);
	  }

	  return decodedLevels;
	}

	// Decode the supplied encoded polyline and levels.
	function decodePath() {
	  var encodedPolyline = document.getElementById('encodedPolyline').value;
	  var encodedLevels = document.getElementById('encodedLevels').value;

	  if (encodedPolyline.length==0) {
	    return;
	  }

	  var decodedPath = google.maps.geometry.encoding.decodePath(encodedPolyline);
	  var decodedLevels = decodeLevels(encodedLevels);

	  if (decodedPath.length == 0) {
	    return;
	  }

	  // If no levels are supplied, default to use level 3, the least restrictive.  
	  if (decodedLevels.length == 0) {
	    for (i = 0; i < decodedPath.length ; i++) {
	      decodedLevels[i] = 3;
	    }
	  }

	  if (decodedPath.length != decodedLevels.length) {
	    alert('Point count and level count do not match');
	    return;
	  }

	  deleteAllLocations();

	  for (var i = 0; i < decodedPath.length; ++i) {
	    addLocation(decodedPath[i].lat(), decodedPath[i].lng(), decodedLevels[i]);
	  }
	  showEncoding();
	  var mapBounds = displayPath.getBounds();
	  map.fitBounds(mapBounds);
	}

	google.maps.Polyline.prototype.getBounds = function() {
	  var bounds = new google.maps.LatLngBounds();
	  this.getPath().forEach(function(e) {
	    bounds.extend(e);
	  });
	  return bounds;
	};

	function centerMap() {
	  var address = document.getElementById('txtAddress').value;

	  if (address.length > 0) {
	    var geocoder = new google.maps.Geocoder();
	    
	    geocoder.geocode({ 'address': address }, function(results, status) {
	      if (status == google.maps.GeocoderStatus.OK) {
	        map.setCenter(results[0].geometry.location);
	      } else {
	        alert("Address not found" + status.toString());
	      }
	    });
	  }
	}

	// Move the map to the selected location in the location list.
	function jumpToLocation() {
	  var locationList = document.getElementById('locations');
	  if (locationList.selectedIndex >= 0) {
	    var location = locations[locationList.selectedIndex];
	    map.setCenter(new google.maps.LatLng(location.Latitude, location.Longitude));
	  }
	}
	
	function submitTrack()
	{
		
		//alert("submitTrack");
		var latLong = document.getElementById("latLong");
		var trackListObj = document.getElementById("locations");
		//alert(validateForm());
		if(validateForm()){
		//if(true){		
			var track='';
			for(i=0; i<trackListObj.options.length;i++)
			{
				if(i==0)
					track = track + trackListObj.options[i].text;
				else
					track = track + "#"+trackListObj.options[i].text;
			}
			latLong.value = track;
			return true;
		} 
		return false;
	}
	
	function validateForm()
	{
		
		var flag = true;
		var latLong = document.getElementById("latLong");
		var locObj = document.getElementById("locations");
		var zoneObj = document.getElementById("zoneId");
		var wardObj = document.getElementById("wardId");
		var appContextPath = "<%= request.getContextPath()%>";
		jsonrpc = new JSONRpcClient(appContextPath + "/JSON-RPC");
				
 		if(zoneObj.options[zoneObj.selectedIndex].value=='none'){
			//enable select zone error
			flag=false;
			document.getElementById("zoneErrMsg").style.display = 'block';
		}
 		else
 		{
 			document.getElementById("zoneErrMsg").style.display = 'none';
 		}
 		
		if(wardObj.options[wardObj.selectedIndex].value=='none'){
			//enable select ward error
			flag=false;
			document.getElementById("wardErrMsg").style.display = 'block';
		}
 		else
 		{
 			document.getElementById("wardErrMsg").style.display = 'none';
 		}
		if(locObj.length <= 1){
			//enable location list error msg
			flag=false;
			document.getElementById("trackErrMsg").style.display = 'block';
		}
 		else
 		{
 			document.getElementById("trackErrMsg").style.display = 'none';
 		}
		/*if(document.getElementById('superviserId').value.length != 0)
		{
			//enable superviserId error.
			var result = jsonrpc.wards.validateEmp(document.getElementById('superviserId').value);
			if(!result)
			{
				flag=false;
				document.getElementById("superviserErrMsg").style.display = 'block';
			}
			else{
				document.getElementById("superviserErrMsg").style.display = 'none';
			}
			
		}
 		else
 		{
 			document.getElementById("superviserErrMsg").style.display = 'none';
 		}
		if(document.getElementById('sweeperId').value.length==0)
		{
			//enable sweeperId error.
			flag=false;
			document.getElementById("sweeperErrMsg").style.display = 'block';
		}
 		else
 		{
 			var result = jsonrpc.wards.validateEmp(document.getElementById('sweeperId').value);
			if(!result)
			{
				flag=false;
				document.getElementById("sweeperIdErrMsg").style.display = 'block';
			}else{
				document.getElementById("sweeperIdErrMsg").style.display = 'none';
			}

 			document.getElementById("sweeperErrMsg").style.display = 'none';
 		}*/ 
		//alert(flag);
		return flag; 
	}
	
	function clearErrMsg(){
		document.getElementById("zoneErrMsg").style.display = 'none';
		document.getElementById("wardErrMsg").style.display = 'none';
		document.getElementById("superviserErrMsg").style.display = 'none';
		document.getElementById("sweeperErrMsg").style.display = 'none';
		document.getElementById("sweeperIdErrMsg").style.display = 'none';
		document.getElementById("trackErrMsg").style.display = 'none';
	}
	
	function loadWardList(ref, wardId) {
		try
		
		{
			//alert("laodWardLIst");
			var appContextPath = "<%= request.getContextPath()%>";
			jsonrpc = new JSONRpcClient(appContextPath + "/JSON-RPC");
			var zoneId = ref.options[ref.options.selectedIndex].value;   
			if('none' == zoneId)  {
				document.getElementById('wardId').disabled="disabled";
				}else{
			var result = jsonrpc.wards.getWardList(zoneId);
			//alert(result);
			var eWardObj = document.getElementById(wardId);
			var eventLength = eWardObj.options.length;
			
			for(i=eWardObj.options.length -1;i>=0 ;i--)
			{
					eWardObj.options[i] = null;
			}
			eWardObj.options[0] = new Option('Select Ward','none');
			
			if( result !=null && result.list.length > 0)
			{

				for(i=0,j=1;i < result.list.length;i++)
				{
					var id = result.list[i].fieldName;
					var value = result.list[i].fieldValue;
					eWardObj.options[j++] = new Option(value,id);
				}
			}
				}
		}
		catch(e) {
		alert(e);
		}
		zoneId = ref.options[ref.options.selectedIndex].value; 
		if('none' == zoneId)  {
		   document.getElementById('wardId').disabled="disabled";
	   	}else{
	   	 document.getElementById('wardId').disabled=false;
	   	}
		}

	function setWardLocation(){
		var ref = document.getElementById('wardId');
		var wardId = ref.options[ref.options.selectedIndex].value; 
		if('none' != wardId)  {
			var appContextPath = "<%= request.getContextPath()%>";
			jsonrpc = new JSONRpcClient(appContextPath + "/JSON-RPC");
			var wardObj = jsonrpc.wards.getWard(wardId);
			var latLong = wardObj.latLong;
			if(latLong){
				setMapLocation(latLong.split(",")[0],latLong.split(",")[1]);
			}
	   	}
	}
	function setMapLocation(lat,lang)
	{
		map.setCenter(new google.maps.LatLng(lat, lang));
	}

	function showMap(trackPointsString){
		getTrackPointsArray(trackPointsString);
		//displayEmpTrack(getTrackPointsArray(trackPointsString));
		
	}
	function getTrackPointsArray(trackPoints) {
		var latLongPoints = new Array()
		var points = trackPoints.split('#');
		for(var i=0; i < points.length; i++ ) {
			var latLng = points[i].split(',');
			var lat = parseFloat(latLng[0].trim());
			var lng = parseFloat(latLng[1].trim());
			latLongPoints.push(new google.maps.LatLng(lat,lng));
			addLocation(lat, lng, 2);
		}
		return latLongPoints;
	}

	function displayEmpTrack(trackPoints) {
		
		//document.getElementById('map_canvas').style.display = 'none'
		map.setCenter(trackPoints[0]);
		map.setZoom(15);
	    var color = "#3b2ee8";
	
		displayPath.setPath(trackPoints);
		displayPath.strokeColor = color;
		displayPath.startPointMarker = tempMarker;
	
	
		displayPath.setMap(map);
		
		startMarker.setPosition(trackPoints[0]);
		startMarker.setMap(map);
		
		endMarker.setPosition(trackPoints[trackPoints.length-1]);
		endMarker.setMap(map)

	}
	
	</script>

</head>

<body onload="initialize()" onunload="GUnload()">
  
		
<div id="mainCnt">
	<s:form id="createTrack" action="addTrack.action" onsubmit="return submitTrack()">

	<div>
		<div id="content-main">
			<table>
				<tr>
					<td></td>
					<td><div id="zoneErrMsg" class="errorMsg">Please Select Zone</div></td>
					<td></td>
					<td><div id="wardErrMsg" class="errorMsg">Please Select Prabhag</div></td>
					<td></td>
				</tr>
				<tr>
					<td><b>&nbsp;&nbsp;Select Zone :</b></td>
					<td><s:select id="zoneId" name="track.zoneId" cssClass="dropdown" 
                           value="%{track.zoneId}" headerKey="none" headerValue="Select Zone" 
		 			 onchange="javascript:loadWardList(this,'wardId');" 
		  			list="zoneList" listKey="id" listValue="name" onselect="true"/>
		  			<span class="mandetory">*</span>					
					</td>
					<td><b>&nbsp;&nbsp;Select Prabhag :</b></td>
					<td><s:select  required="true" 
						name="track.wardId" id="wardId" cssClass="dropdown"
					list="wardList" listKey="id" listValue="name"
					headerKey="none" headerValue="Select Prabhag"
					value="%{track.wardId}"  /><span class="mandetory">*</span>
					</td>
					<td>	
						<div class="buttonwrapper">
							<a class="btn-info btn"" href="javascript:setWardLocation()"><span>Go</span></a>
						</div>
						<!-- <input type="button" value="Go" onclick="setWardLocation()" id="button_css" />-->
					</td>
			</tr>
		</table>
			<div id="map_canvas" style="margin: 10px; height: 500px"></div>
		</div>
		<div id="content-sidebar" style="padding-top: 0px;">
		<div id="createTrackSideBar" style="display:block; margin-left:10px">
			<s:hidden name="track.id" id="id" value="%{track.id}"/>
			<s:hidden name="track.latLong" id="latLong" value="%{track.latLong}"/>
			<input id="txtLatitude" maxlength="11" type="hidden" class="inputField"/>
			<input id="txtLongitude" maxlength="11" type="hidden" class="inputField"/>
			<input id="txtLevel" type="hidden" size=3 value="3"/>
			<div>
				<b>Track Type:&nbsp;&nbsp;&nbsp;</b>
				<s:select label="" 
			  	name="track.trackType" list="#{'None':'None','500mtr':'500Mtr','700mtr':'700Mtr','900mtr':'900Mtr'}"/>
			  	
			</div>
			<div>
				
				<b>Prabhag No:&nbsp;&nbsp;&nbsp;</b>
				
			<s:textfield name="track.prabhagNumber" maxlength="6" cssStyle="width:50px;" cssClass="inputField" 
                      	  value="%{track.prabhagNumber}" id="prabhagNumber"  />	
			</div>
			<div>
				<div id="superviserErrMsg" class="errorMsg">Please enter valid superviser id.</div>
				<b>Supervisor Id:</b>
				
				<s:textfield name="track.superviserId" maxlength="6" cssStyle="width:50px;" cssClass="inputField" 
                      	  value="%{track.superviserId}" id="superviserId"  />	
			</div>
			<div>
				<div id="sweeperErrMsg" class="errorMsg">Please enter sweeper id.</div>
				<div id="sweeperIdErrMsg" class="errorMsg">Please enter valid sweeper id.</div>
				<b>Sweeper Id:&nbsp;&nbsp;&nbsp;&nbsp;</b>
				<s:textfield name="track.sweeperId" maxlength="6" cssStyle="width:50px;" cssClass="inputField" 
                      	  value="%{track.sweeperId}" id="sweeperId"  />	
			</div>
			<div>
				<b>Sweeper Name:</b></br>
				<!--<input id="sweeperName" value="%{track.sweeperName}" name="track.sweeperName" type="text" class="inputField"/> -->
				<s:textfield name="track.sweeperName"  cssClass="inputField" 
                      	  value="%{track.sweeperName}" id="sweeperName"  />	
				<!--<s:textfield key="track.sweeperName" id="sweeperName" cssClass="inputField"/> -->
			</div>
			<div>
				<b>Supervisor Name:</b></br>
				
				<s:textfield name="track.superviserName"  cssClass="inputField" 
                      	  value="%{track.superviserName}" id="superviserName"  />
			</div>
			
			<div>
				<b>Bit:</b></br>
				<s:textarea cols="25" rows="2" name="track.bit" id="bit"/>
			</div>
			
			<div>
				<b>Remarks</b></br>
				<s:textarea cols="25" rows="2" id="remarks" name="track.remarks"/>
			</div>
			
			
			<div style="line-height: 1.1em;">
				Please define track points & click arrow button to add track points.
			</div>
			<div>
				<div id="trackErrMsg" class="errorMsg">Please add minimum two points.</div>
			</div>
			<div style="width:100%">
				<div style="float:left;margin-top:60px;margin-right:5px">
					<img alt="Add Track Points" src="images/rightarrow.png" onclick="addLocationFromInput()"/>
				</div >
				<div style="float:left">
					<div style="margin-bottom:5px">
					<select id="locations" size="6"  onchange="highlight(this.selectedIndex)" 
					style="width: 14em;" ondblclick="jumpToLocation()"></select></br>
					</div>
					<div >
						<div style="margin-right:5px;float:left">
							<a class="btn-info btn" href="javascript:deleteLocation()"><span>Remove</span></a>
						</div>
						<div style="width:5px;float:left">&nbsp;</div>
						<div style="float:left">
							<a class="btn-info btn" href="javascript:deleteAllLocations()"><span>Remove All</span></a>
						</div>
					</div>	
				</div>
			</div>
			<div>
				
			</div>	
			
			<div>
				<s:submit theme="simple" id="submitBtn" cssStyle="margin-top: 15px;" value="Submit" cssClass="button_css"/>
			</div>
			
			
		</div>
	</div>
	</div>	
	</s:form>
</div>		
  
</body>
</html>
